<template>
  <div>
    <!-- <h2>获取并解密 Excel 数据</h2>
    <button @click="clearCache">清除缓存并重新获取</button>
    <pre v-if="decryptedData">{{ decryptedData }}</pre> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { fetchDecryptedExcelData } from '../api/excelService.js';

const decryptedData = ref(null);
const CACHE_KEY = 'excelDataCache';
const CACHE_EXPIRATION = 60 * 60 * 1000; // 缓存 1 小时

// 读取缓存数据
const loadFromCache = () => {
  const cached = localStorage.getItem(CACHE_KEY);
  if (cached) {
    const parsedCache = JSON.parse(cached);
    if (Date.now() - parsedCache.timestamp < CACHE_EXPIRATION) {
      decryptedData.value = parsedCache.data;
      // console.log(decryptedData.value);
      return true;
    } else {
      localStorage.removeItem(CACHE_KEY); // 过期则清除缓存
    }
  }
  return false;
};

// 请求数据并缓存




const fetchData = async () => {
  const data = await fetchDecryptedExcelData();
  if (data) {
    decryptedData.value = JSON.stringify(data, null, 2);
    localStorage.setItem(CACHE_KEY, JSON.stringify({ data: decryptedData.value, timestamp: Date.now() }));
  }
};

// 清除缓存并重新请求
const clearCache = () => {
  localStorage.removeItem(CACHE_KEY);
  fetchData();
};

// 组件挂载时检查缓存或请求数据
onMounted(() => {
  console.log('组件挂载');
  if (!loadFromCache()) {
    console.log('数据未缓存或已过期，正在请求数据');
    fetchData();
  }
});
</script>

<style scoped>
button {
  padding: 8px 16px;
  font-size: 16px;
  margin-bottom: 10px;
  cursor: pointer;
}

pre {
  background: #f4f4f4;
  padding: 10px;
  border-radius: 5px;
}
</style>
